package com.isyscore.os.core.sqlcore;

public class MSSQLBuilder implements Builder {

    private static final String CREATE_TABLE = "CREATE TABLE %s ( \n";

    private static final String COL_DEF = "[%s] %s NULL,\n";

    private static final String INSERT_TABLE = "INSERT INTO %s (\n";

    private static final String VALUES = "VALUES(\n";

    private StringBuilder _sql1;

    private StringBuilder _sql2;

    @Override
    public Builder createTable(String tableName) {
        this._sql1 = new StringBuilder();
        this._sql1.append(String.format(CREATE_TABLE, tableName));
        _sql2 = null;
        return this;
    }

    @Override
    public Builder addCol(String colName, String colType, String comment) {
        this._sql1.append(String.format(COL_DEF, colName, colType));
        return this;
    }

    @Override
    public Builder insert(String table) {
        this._sql1 = new StringBuilder(String.format(INSERT_TABLE, table));
        this._sql2 = new StringBuilder(VALUES);
        return this;
    }

    @Override
    public Builder addValue(String col, Object val) {
        this._sql1.append("[" + col + "],");
        if (val instanceof String) {
            this._sql2.append("N'" + val + "',");
        }else {
            this._sql2.append(val + ",");
        }
        return this;
    }

    @Override
    public String build() {
        if (this._sql1 != null) {
            int index = this._sql1.lastIndexOf(",");
            this._sql1.delete(index, index + 1);
            this._sql1.append("\n)");
        }
        if (this._sql2 != null) {
            int index = this._sql2.lastIndexOf(",");
            this._sql2.delete(index, index + 1);
            this._sql2.append("\n)");
        }
        if (_sql2 != null) {
            _sql1.append("\n").append(_sql2);
        }
        return _sql1.toString();
    }
}
